#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "Trace.hpp"

static bool alwaysTrace = false;
TraceStream trace;

void setAlwaysTrace(bool enabled)
{
	alwaysTrace = enabled;
	if(enabled) {
		trace.flush();
		trace.directToStdout = true;
	}
}
std::ostream *traceOutput = NULL;
std::string traceOutputName = "-";

static void closeTraceFile()
{
	std::ofstream *outFile = dynamic_cast<std::ofstream*>(traceOutput);
	if(outFile) {
		outFile->close();
		delete traceOutput;
		traceOutput = NULL;
	}
}

void initTrace()
{
	if(!traceOutput) {
		if(traceOutputName == "-") {
			traceOutput = &std::cout;
		} else {
			traceOutput = new std::ofstream(traceOutputName.c_str());
			if(traceOutput->fail()) {
				std::cerr << "Failed to open debug output file.\n";;
				exit(1);
			}
			atexit(closeTraceFile);
		}
	}
}

TraceStream::TraceStream()
{
	directToStdout = false;
}

void TraceStream::flush()
{
	if(!buf.str().length())
		return;
	if(!traceOutput)
		initTrace();
	(*traceOutput) << buf.str();
	buf.str("");
}

void TraceStream::clear()
{
	buf.str("");
	if(!alwaysTrace)
		directToStdout = false;
}

void TraceStream::close()
{
	closeTraceFile();
}

